﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq.Expressions;
using VisualWip.Core.Utils;

namespace VisualWip.TFS2010PersistanceProvider
{
    public class OpenDialogViewModel : INotifyPropertyChanged
    {
        private bool _openEnabled;
        private TFSConnectionSettingsPathView _selectedSetting;

        public OpenDialogViewModel(ObservableCollection<TFSConnectionSettingsPathView> tfsConnectionSettingsPathViews)
        {
            Settings = tfsConnectionSettingsPathViews;
            foreach (TFSConnectionSettingsPathView settingsPathView in Settings)
            {
                settingsPathView.PropertyChanged += SettingPropertyChanged;
            }
        }

        public ObservableCollection<TFSConnectionSettingsPathView> Settings { get; private set; }

        public TFSConnectionSettingsPathView SelectedSetting
        {
            get { return _selectedSetting; }
            set
            {
                _selectedSetting = value;
                OpenEnabled = _selectedSetting != null;
            }
        }

        public bool OpenEnabled
        {
            get { return _openEnabled; }
            set
            {
                if (value != _openEnabled)
                {
                    _openEnabled = value;
                    OnPropertyChanged(this, () => OpenEnabled);
                }
            }
        }

        private void SettingPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var settingsPathView = sender as TFSConnectionSettingsPathView;
            if (settingsPathView != null && settingsPathView.IsSelected)
                SelectedSetting = settingsPathView;
        }

        protected void OnPropertyChanged<T>(object sender, Expression<Func<T>> property)
        {
            PropertyHelper.OnPropertyChanged(sender, PropertyChanged, property);
        }

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}